<template>
	<view>
		<view class="cart-window" :class="(cartAttr.show===true ? 'on' : '')">
			<view class="borRadius14 cartBox shoppingCart">
					<view
						v-if="cartList.valid.length > 0"
						class='nav acea-row row-between-wrapper'>
						<view v-if="cartList.valid.length > 0"
							class='administrate acea-row row-center-wrapper' @click='manage'>{{ footerswitch ? '管理' : '取消'}}
						</view>
						<view v-if="!footerswitch"> <text class='num font-color' @click="subDel">删除</text></view>
					</view>
					<view v-if="cartList.valid.length > 0" class="pad30">
						<scroll-view scroll-y="true" scroll-with-animation='true' style="max-height: 540rpx;">
					
						<view class='list'>
							<checkbox-group @change="checkboxChange">
								<block v-for="(item,index) in cartList.valid" :key="index">
									<view class='item acea-row row-between-wrapper'>
										<checkbox :value="(item.id).toString()" :checked="item.checked"
											v-if="!footerswitch" />
										<view hover-class='none'class='picTxt acea-row row-between-wrapper'>
											<view class='pictrue'>
												<image :src='item.image'></image>
											</view>
											<view class='text'>
												<view class='line1' :class="item.attrStatus?'':'reColor'">{{item.storeName}}
												</view>
												<view class='infor line1' v-if="item.suk">属性：{{item.suk}}</view>
												<view class='money' v-if="item.attrStatus">￥{{item.price}}</view>
											</view>
											<view class='carnum acea-row row-center-wrapper' v-if="item.attrStatus">
												<view class="reduce" :class="item.numSub ? 'on' : ''"
													@click.stop='subCart(index)'>-</view>
												<view class='num'>{{item.cartNum}}</view>
												<view class="plus" :class="item.numAdd ? 'on' : ''"
													@click.stop='addCart(index)'>+</view>
											</view>
										</view>
									</view>
								</block>
							</checkbox-group>
						</view>
						</scroll-view>
					</view>
				</view>
		</view>
		<view class="bottom" v-if="cartCount > 0">
			<view class="cartStatistic">
				<view class="cartNum" @click="initData">
					<image src="../../static/images/3-001.png"></image>
					<span v-if="cartCount > 0">{{cartCount}}</span>
				</view>
				
				<view class="cartMoney" v-if="cartCountMoney>0">合计：<span class="font-color-red">￥{{cartCountMoney}}</span></view>
			</view>
			
			<view class="orderBtn" @click="subOrder">去结账</view>
		</view>
		<view class="mask" @touchmove.prevent :hidden="!cartAttr.show" @click="cartAttr.show=false"></view>
	</view>
</template>

<script>
	let sysHeight = 0
	import {
		getAllValidList,
		getCartCounts,
		changeCartNum,
		cartDel,
		getResetCart
	} from '@/api/order.js';
	import {
		getProductHot,
		collectAll,
		getProductDetail
	} from '@/api/store.js';
	import {
		toLogin
	} from '@/libs/login.js';
	import {
		mapGetters
	} from "vuex";
	import recommend from '@/components/recommend';
	import productWindow from '@/components/productWindow';
	// #ifdef MP
	import authorize from '@/components/Authorize';
	// #endif
	
	export default {
		name:"cartWindow",
		components: {
			recommend,
			productWindow,
			// #ifdef MP
			authorize
			// #endif
		},
		watch:{
			  "param.cartNumFlag": function(nVal) {
			      this.getCartNum()
			      this.getCartCountMoney()
			  }
		},
		
		computed: mapGetters(['isLogin']),
		props:{
			param: {
				type: Object,
				default: () => {}
			},
		},
		
		data() {
			return {
				cartCount: 0,
				cartCountMoney: 0,
				goodsHidden: false,
				footerswitch: true,
				cartList: {
					valid: [],
				},
				isAllSelect: false, //全选
				selectValue: [], //选中的数据
				isAuto: false, //没有授权的不会自动授权
				isShowAuth: false, //是否隐藏授权
				cartAttr: {
					show: false,
				},
				cartId: 0,
				product_id: 0,
				sysHeight: sysHeight,
				isCreated: false,
			};
		},
		
		created() {
			this.initData();
		},
		
		methods: {
			initData: function() {
				if (this.isLogin == true) {
					this.footerswitch = true;
					this.cartList = {valid: [],},
					this.isAllSelect = false; //全选
					this.selectValue = []; //选中的数据
					this.isShowAuth = false;
					if(this.cartAttr.show){
						this.cartAttr.show = false;
						return
					}else{
						this.getCartList();
					}
				};
			},
			
			subDel: function(event) {
				let that = this,
					selectValue = that.selectValue;
				if (selectValue.length > 0)
					cartDel(selectValue).then(res => {
						that.cartList.valid = [];
						that.getCartList();
						//通知父级购物车数量更新
						that.$emit("event_cart_change");
					});
				else
					return that.$util.Tips({
						title: '请选择产品'
					});
			},
			// 立即下单
			async subOrder(event) {
				let that = this;
				let validList = await this.getCartData();
				let validCartIds = validList.filter(item=>item.attrStatus).map(item=>{
					return {"shoppingCartId": item.id}
				})
				if (validCartIds.length > 0) {
					that.getPreOrder(validCartIds);
				} else {
					return that.$util.Tips({
						title: '请选择产品'
					});
				}
			},
			/**
			 * 预下单
			 */
			getPreOrder(validCartIds) {
				this.$Order.getPreOrder("shoppingCart", validCartIds);
			},
			checkboxAllChange: function(event) {
				let value = event.detail.value;
				if (value.length > 0) {
					this.setAllSelectValue(1)
				} else {
					this.setAllSelectValue(0)
				}
			},
			setAllSelectValue: function(status) {
				let that = this;
				let selectValue = [];
				let valid = that.cartList.valid;
				if (valid.length > 0) {
					let newValid = valid.map(item => {
						if (status) {
							if (that.footerswitch) {
								if (item.attrStatus) {
									item.checked = true;
									selectValue.push(item.id);
								} else {
									item.checked = false;
								}
							} else {
								item.checked = true;
								selectValue.push(item.id);
							}
							that.isAllSelect = true;
						} else {
							item.checked = false;
							that.isAllSelect = false;
						}
						return item;
					});
					that.$set(that.cartList, 'valid', newValid);
					that.selectValue = selectValue;
				}
			},
			checkboxChange: function(event) {
				let that = this;
				let value = event.detail.value;
				let valid = that.cartList.valid;
				let arr1 = [];
				let arr2 = [];
				let arr3 = [];
				let newValid = valid.map(item => {
					if (that.inArray(item.id, value)) {
						if (that.footerswitch) {
							if (item.attrStatus) {
								item.checked = true;
								arr1.push(item);
							} else {
								item.checked = false;
							}
						} else {
							item.checked = true;
							arr1.push(item);
						}
					} else {
						item.checked = false;
						arr2.push(item);
					}
					return item;
				});
				if (that.footerswitch) {
					arr3 = arr2.filter(item => !item.attrStatus);
				}
				that.$set(that.cartList, 'valid', newValid);
				// let newArr = that.cartList.valid.filter(item => item.attrStatus);
				that.isAllSelect = newValid.length === arr1.length + arr3.length;
				that.selectValue = value;
			},
			inArray: function(search, array) {
				for (let i in array) {
					if (array[i] == search) {
						return true;
					}
				}
				return false;
			},
		
			subCart: function(index) {
				let that = this;
				let item = that.cartList.valid[index];
				item.cartNum = Number(item.cartNum) - 1;
				if(item.cartNum === 0){
					let values = [];
					values.push(item.id)
					cartDel(values).then(res => {
						that.cartList.valid = [];
						that.getCartList();
						//通知父级购物车数量更新
						that.$emit("event_cart_change");
					});
				}else{
					that.setCartNum(item.id, item.cartNum, function(data) {
						that.cartList.valid[index] = item;
						that.getCartNum();
						that.getCartCountMoney();
						//通知父级购物车数量更新
						that.$emit("event_cart_change");
					});
				}
			},
			addCart: function(index) {
				let that = this;
				let item = that.cartList.valid[index];
				item.cartNum = Number(item.cartNum) + 1;
				let productInfo = item;
				if (item.cartNum >= item.stock) {
					item.cartNum = item.stock;
					item.numAdd = true;
					item.numSub = false;
				} else {
					item.numAdd = false;
					item.numSub = false;
				}
				that.setCartNum(item.id, item.cartNum, function(data) {
					that.cartList.valid[index] = item;
					that.getCartNum();
					that.getCartCountMoney();
					//通知父级购物车数量更新
					that.$emit("event_cart_change");
				});
			},
			setCartNum(cartId, cartNum, successCallback) {
				let that = this;
				changeCartNum(cartId, cartNum).then(res => {
					successCallback && successCallback(res.data);
				});
			},
			getCartNum: function() {
				let that = this;
				getCartCounts(true, 'sum').then(res => {
					that.cartCount = res.data.count;
				});
			},
			//网络请求--查询购物车列表
			getCartData(data) {
				return new Promise((resolve, reject) => {
					getAllValidList(data).then((res) => {
						resolve(res.data);
					}).catch(function(err) {
						this.$util.Tips({
							title: err
						});
					})
				});
			},
			async getCartCountMoney(){
				let validList = await this.getCartData({isValid: true});
				let total = 0
				validList.forEach((item) => {
				  total += parseFloat(item.price) * item.cartNum;
				});
				this.cartCountMoney = total
			},
			
			//先获取购物车数量+获取购物车列表
			async getCartList() {
				let that = this;
				uni.showLoading();
				getCartCounts(true, 'sum').then(async c => {
					that.cartCount = c.data.count;
					if(that.cartCount === 0){
						that.cartAttr.show = false;
						uni.hideLoading();
						return;
					}
					let validList = await this.getCartData({isValid: true});
					let total = 0
					validList.forEach((item) => {
					  total += parseFloat(item.price) * item.cartNum;
					});
					that.cartCountMoney = total
					
					let numSub = [{
						numSub: true
					}, {
						numSub: false
					}];
					let numAdd = [{
							numAdd: true
						}, {
							numAdd: false
						}],
						selectValue = [];
					if (validList.length > 0) {
						for (let index in validList) {
							if (validList[index].cartNum == 1) {
								validList[index].numSub = true;
							} else {
								validList[index].numSub = false;
							}
							let productInfo = validList[index];
							let stock = validList[index].stock ? validList[index].stock : 0;
							if (validList[index].cartNum == stock) {
								validList[index].numAdd = true;
							} else if (validList[index].cartNum == validList[index].stock) {
								validList[index].numAdd = true;
							} else {
								validList[index].numAdd = false;
							}
							if (validList[index].attrStatus) {
								validList[index].checked = true;
								selectValue.push(validList[index].id);
							} else {
								validList[index].checked = false;
							}
						}
					}
					that.$set(that.cartList, 'valid', validList);
					that.selectValue = selectValue;
					let newArr = validList.filter(item => item.attrStatus);
					that.isAllSelect = newArr.length == selectValue.length && newArr.length;
					uni.hideLoading();
					if(!that.isCreated){
						that.isCreated = true
						return
					}
					that.cartAttr.show = true;
				});
			},
		
			manage: function() {
				let that = this;
				that.footerswitch = !that.footerswitch;
				let arr1 = [];
				let arr2 = [];
				let newValid = that.cartList.valid.map(item => {
					if (that.footerswitch) {
						if (item.attrStatus) {
							if (item.checked) {
								arr1.push(item.id);
							}
						} else {
							item.checked = false;
							arr2.push(item);
						}
					} else {
						if (item.checked) {
							arr1.push(item.id);
						}
					}
					return item;
				});
				that.cartList.valid = newValid;
				if (that.footerswitch) {
					that.isAllSelect = newValid.length === arr1.length + arr2.length;
				} else {
					that.isAllSelect = newValid.length === arr1.length;
				}
				that.selectValue = arr1;
			},
		},
		
	}
</script>

<style lang="scss" sc>
	.cart-window{
		position: fixed;
		bottom: 0rpx;
		width: 100%;
		left: 0;
		background-color: #fff;
		z-index: 55;
		border-radius: 16rpx 16rpx 0 0;
		//#ifdef MP
		padding-bottom: 140rpx;
		//#endif
		//#ifdef H5
		padding-bottom: 240rpx;
		//#endif
		transform: translate3d(0, 100%, 0);
		transition: all .3s cubic-bezier(.25, .5, .5, .9);
	}
	
	.cart-window.on {
		transform: translate3d(0, 0, 0);
	}

	.shoppingCart .nav {
		height: 100rpx;
		background-color: #fff;
		padding: 0 40rpx;
		-webkit-box-sizing: border-box;
		box-sizing: border-box;
		font-size: 28rpx;
		color: #282828;
		display: flex;
		justify-content: space-between;
		border-top-left-radius: 14rpx;
		border-top-right-radius: 14rpx;
	}

	.shoppingCart .nav .administrate {
		font-size: 28rpx;
		color: #333333;
	}
	
	.shoppingCart .list {
		width: 100%;
		overflow: hidden;
		border-bottom-left-radius: 14rpx;
		border-bottom-right-radius: 14rpx;
	}
	
	.shoppingCart .list .item {
		background-color: #fff;
		margin-bottom: 10rpx;
		display: flex;
		justify-content: space-around;
	}
	
	.shoppingCart .list .item .picTxt {
		width: 90%;
		position: relative;
	}
	
	.shoppingCart .list .item .picTxt .pictrue {
		width: 120rpx;
		height: 120rpx;
	}
	
	.shoppingCart .list .item .picTxt .pictrue image {
		width: 100%;
		height: 100%;
		border-radius: 6rpx;
	}
	
	.shoppingCart .list .item .picTxt .text {
		width: calc(100% - 140rpx);
		font-size: 28rpx;
		color: #282828;
		font-weight: bold;
	}
	
	.shoppingCart .list .item .picTxt .text .reColor {
		color: #999;
	}
	
	
	.shoppingCart .list .item .picTxt .text .infor {
		font-size: 24rpx;
		color: #999999;
		margin-top: 4rpx;
	}
	
	.shoppingCart .list .item .picTxt .text .money {
		font-size: 30rpx;
		color: #E93323;
		margin-top: 14rpx;
		font-weight: 600;
	}
	
	.shoppingCart .list .item .picTxt .carnum {
		// height: 47rpx;
		position: absolute;
		bottom: 7rpx;
		right: 0;
	}
	
	.shoppingCart .list .item .picTxt .carnum view {

		border-radius: 40rpx;
		height: 40rpx;
		width: 40rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-weight: bold;
		padding-bottom: 6rpx;
		
	}
	
	.shoppingCart .list .item .picTxt .carnum .reduce {

		background-color: white;
		border: 4rpx solid $theme-color;
		color: $theme-color;
		
	}
	
	.shoppingCart .list .item .picTxt .carnum .reduce.on {

	}
	
	.shoppingCart .list .item .picTxt .carnum .plus {
		background-color: $theme-color;
		color: white;
	}
	
	.shoppingCart .list .item .picTxt .carnum .num {
		color: #282828;
		min-width: 80rpx;
		padding-bottom: 0;
	}
	
	.bottom{
		height: 96rpx;
		position: fixed;
		//#ifdef MP
		bottom: 0;
		//#endif
		//#ifdef h5
		bottom: 96rpx;
		//#endif
		left: 0;
		right: 0;
		background-color: #fff;
		border-top: 2rpx #dfdfdf solid;
		display: flex;
		justify-content: space-between;
		z-index: 77;
		.cartStatistic{
			display: flex;
			align-items: center;
			
			.cartMoney{
				margin-left: 20rpx;
				font-size: 28rpx;
				font-weight: bold;
				span{
					font-size: 36rpx;
					font-weight: bold;
				}
			}
			
			.cartNum{
				height: 100%;
				display: flex;
				align-items: center;
				margin-left: 40rpx;
				position: relative;
				padding: 0 20rpx;
				image{
					width: 44rpx;
					height: 44rpx;
				}
				span{
					position: absolute;
					font-size: 24rpx;
					top: 0;
					right: 0;
					min-width: 32rpx;
					padding: 0 4rpx;
					height: 32rpx;
					border-radius: 16rpx;
					color: white;
					background-color: $theme-color;
					text-align: center;
				}
				
			}
			
		}

		.orderBtn {
			font-size: 30rpx;
			width: 300rpx;
			height: 100%;
			display: flex;
			font-weight: bold;
			justify-content: center;
			align-items: center;
			color: #fff;
			background-color: $theme-color;
		}
	}
	
</style>